import { _decorator, Component } from 'cc';
import ResLoader, { AssetBundle, BundleCallback, BundlesCallback, ErrorCallback } from '../../../../sgame/resource/ResLoader';
import { ProgressBar } from 'cc';
import { Label } from 'cc';
import { Prefab } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('UILoading')
export class UILoading extends Component {
    private _bundleNames: string[] = [];
    private _curIdx: number = 0;
    private _loadingBundleName: string;
    private _bundles: AssetBundle[] = [];

    public _onComplete: BundlesCallback;
    public _onCompleteOne: BundleCallback;
    public _onError: ErrorCallback;

    @property(ProgressBar)
    private progress: ProgressBar;

    @property(Label)
    private label: Label;

    get bundleNames(): string[] {
        return this._bundleNames;
    }

    set bundleNames(value: string | string[]) {
        if (typeof value == "string") {
            this._bundleNames = [value];
        } else {
            this._bundleNames = value;
        }
    }

    public loading(bundleNames: string | string[], onComplete?: BundlesCallback, onCompleteOne?: BundleCallback, onError?: ErrorCallback): void {
        this.bundleNames = bundleNames;
        this._onComplete = onComplete;
        this._onCompleteOne = onCompleteOne;
        this._onError = onError;
        this.startLoading();
    }

    public startLoading() {
        this._curIdx = 0;
        this._bundles = [];
        this.next();
        this.node.active = true;
    }

    private next() {
        this._curIdx++;
        this.progress.progress = 0;
        if (this._curIdx > this.bundleNames.length) {
            this._onComplete(this._bundles);
            this.end();
            return;
        }

        this._loadingBundleName = this.bundleNames[this._curIdx - 1];
        this.label.string = `正在加载${this._loadingBundleName}(${this._curIdx}/${this.bundleNames.length})`
        ResLoader.LoadBundle(this._loadingBundleName, (err: Error, bundle: AssetBundle) => {
            if (err) {
                this.end();
                this._onError && this._onError(err);
                return;
            }

            bundle.loadDir('prefabs', Prefab, (finished: number, total: number, _) => {
                // 更新进度条显示
                this.progress.progress = Math.ceil(finished / total);
            }, (err: Error) => {
                if (err) {
                    this.end();
                    this._onError && this._onError(err);
                    return;
                }

                if (this._onCompleteOne) {
                    this._onCompleteOne(bundle);
                }

                this._bundles.push(bundle);
                this.next();
            });
        });
    }

    private end() {
        this.node.active = false;
    }
}